<template>
  <div class="app-container">
    <!-- 导航菜单 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="现金" name="cash">
        <!-- 现金功能栏 -->
        <div class="search-box">
          <el-form :inline="true" :model="searchForm" class="demo-form-inline">
            <div class="form-content">
              <div class="left-content">
                <el-form-item label="编码/名称">
                  <el-input
                    v-model="searchForm.searchKey"
                    placeholder="请输入编码或名称"
                    @input="handleSearchInput"
                  >
                  </el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleSearch"
                    >查询</el-button
                  >
                  <el-button @click="handleReset">重置</el-button>
                </el-form-item>
              </div>
              <div class="right-content">
                <el-form-item>
                  <el-button type="primary" @click="showImportDialog"
                    >导入</el-button
                  >
                  <el-button type="primary" @click="showAddCashDialog"
                    >新增</el-button
                  >
                </el-form-item>
              </div>
            </div>
          </el-form>
        </div>

        <!-- 现金列表 -->
        <div class="table-container">
          <el-table :data="cashList" border style="width: 100%">
            <el-table-column
              prop="accountCoding"
              label="编码"
            ></el-table-column>
            <el-table-column
              prop="accountTitle"
              label="账户名称"
            ></el-table-column>
            <el-table-column prop="currencyId" label="币别">
              <template slot-scope="scope">
                {{ formatCurrency(scope.row) }}
              </template>
            </el-table-column>
            <el-table-column prop="subjectId" label="会计科目">
              <template slot-scope="scope">
                {{ formatSubject(scope.row) }}
              </template>
            </el-table-column>
            <el-table-column prop="codingState" label="启用" width="100">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.codingState"
                  :active-value="1"
                  :inactive-value="2"
                  @change="(val) => handleStatusChange(val, scope.row)"
                >
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleEdit(scope.row, 'cash')"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  class="delete-btn"
                  @click="handleDelete(scope.row, 'cash')"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pagination.currentPage"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="pagination.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pagination.total"
            >
            </el-pagination>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="银行存款" name="bank">
        <!-- 银行存款功能栏 -->
        <div class="search-box">
          <el-form :inline="true" :model="searchForm" class="demo-form-inline">
            <div class="form-content">
              <div class="left-content">
                <el-form-item label="编码/名称">
                  <el-input
                    v-model="searchForm.searchKey"
                    placeholder="请输入编码或名称"
                    @input="handleSearchInput"
                  >
                  </el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleSearch"
                    >查询</el-button
                  >
                  <el-button @click="handleReset">重置</el-button>
                </el-form-item>
              </div>
              <div class="right-content">
                <el-form-item>
                  <el-button type="primary" @click="showImportDialog"
                    >导入</el-button
                  >
                  <el-button type="primary" @click="showAddBankDialog"
                    >新增</el-button
                  >
                  <el-button type="primary" @click="handleReservation"
                    >预约开户</el-button
                  >
                </el-form-item>
              </div>
            </div>
          </el-form>
        </div>

        <!-- 银行存款列表 -->
        <div class="table-container">
          <el-table :data="bankList" border style="width: 100%">
            <el-table-column
              prop="accountCoding"
              label="编码"
            ></el-table-column>
            <el-table-column prop="bankId" label="银行">
              <template slot-scope="scope">
                {{ formatBank(scope.row) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="accountTitle"
              label="账户名称"
            ></el-table-column>
            <el-table-column
              prop="cardNumber"
              label="银行卡号"
            ></el-table-column>
            <el-table-column prop="currencyId" label="币别">
              <template slot-scope="scope">
                {{ formatCurrency(scope.row) }}
              </template>
            </el-table-column>
            <el-table-column prop="subjectId" label="会计科目">
              <template slot-scope="scope">
                {{ formatSubject(scope.row) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleEdit(scope.row, 'bank')"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  class="delete-btn"
                  @click="handleDelete(scope.row, 'bank')"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pagination.currentPage"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="pagination.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pagination.total"
            >
            </el-pagination>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 导入弹框 -->
    <el-dialog
      title="账户导入"
      :visible.sync="importDialogVisible"
      width="400px"
    >
      <div class="import-dialog">
        <!-- 第一步：下载模板 -->
        <div class="import-step">
          <div class="step-number">1</div>
          <div class="step-content">
            <div class="step-title">
              下载导入模板，按照模板格式进行数据整理再导入
            </div>
            <el-button
              type="text"
              icon="el-icon-download"
              class="download-btn"
              @click="downloadTemplate"
            >
              下载模版
            </el-button>
          </div>
        </div>

        <!-- 第二步：选择文件 -->
        <div class="import-step">
          <div class="step-number">2</div>
          <div class="step-content">
            <div class="step-title">选择文件导入</div>
            <el-upload
              class="upload-demo"
              action="#"
              :http-request="handleHttpRequest"
              :before-upload="beforeUpload"
              :show-file-list="true"
              accept=".xls,.xlsx"
            >
              <el-button type="primary" size="small">选择文件</el-button>
            </el-upload>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="importDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUpload">导 入</el-button>
      </div>
    </el-dialog>

    <!-- 新增现金账户弹框 -->
    <el-dialog
      title="新增现金账户"
      :visible.sync="addCashDialogVisible"
      width="50%"
    >
      <el-form
        :model="cashForm"
        :rules="cashRules"
        ref="cashForm"
        label-width="100px"
      >
        <el-form-item label="编码" prop="accountCoding">
          <el-input
            v-model="cashForm.accountCoding"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="账户名称" prop="accountTitle">
          <el-input v-model="cashForm.accountTitle"></el-input>
        </el-form-item>
        <el-form-item label="账户余额" prop="accountBalance">
          <el-input-number
            v-model="cashForm.accountBalance"
            :precision="2"
            :step="0.01"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="币别" prop="currencyId">
          <el-select v-model="cashForm.currencyId" placeholder="请选择币别">
            <el-option
              v-for="item in currencyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="会计科目" prop="subjectId">
          <el-select v-model="cashForm.subjectId" placeholder="请选择会计科目">
            <el-option
              v-for="item in subjectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addCashDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitCashForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 新增银行账户弹框 -->
    <el-dialog
      title="新增银行账户"
      :visible.sync="addBankDialogVisible"
      width="50%"
    >
      <el-form
        :model="bankForm"
        :rules="bankRules"
        ref="bankForm"
        label-width="100px"
      >
        <el-form-item label="编码" prop="accountCoding">
          <el-input
            v-model="bankForm.accountCoding"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="银行" prop="bankId">
          <el-select v-model="bankForm.bankId" placeholder="请选择银行">
            <el-option
              v-for="item in bankOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账户名称" prop="accountTitle">
          <el-input v-model="bankForm.accountTitle"></el-input>
        </el-form-item>
        <el-form-item label="银行卡号" prop="cardNumber">
          <el-input
            v-model="bankForm.cardNumber"
            placeholder="请输入银行卡号"
            @input="formatCardNumber"
            maxlength="23"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="账户余额" prop="accountBalance">
          <el-input-number
            v-model="bankForm.accountBalance"
            :precision="2"
            :step="0.01"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="币别" prop="currencyId">
          <el-select v-model="bankForm.currencyId" placeholder="请选择币别">
            <el-option
              v-for="item in currencyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="会计科目" prop="subjectId">
          <el-select v-model="bankForm.subjectId" placeholder="请选择会计科目">
            <el-option
              v-for="item in subjectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="绑定日期" prop="createdDate">
          <el-date-picker
            v-model="bankForm.createdDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="到期日期" prop="maturityDate">
          <el-date-picker
            v-model="bankForm.maturityDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addBankDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitBankForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addCapitalAccount,
  CapitalAccountList,
  CapitalAccountUpdate,
  addBatchCapitalAccount,
  downloadExcel,
  number,
  uploadExcel,
} from "@/api/system/account";
import axios from "axios";
import { Message } from "element-ui"; // 引入Element UI的消息提示组件，用于提示用户操作结果
import { getCurrentInstance } from "vue";
export default {
  data() {
    return {
      activeTab: "cash",

      searchForm: {
        searchKey: "", // 统一的搜索关键字
        accountCoding: "", // 编码
        accountTitle: "", // 名称
        accountSort: 2, // 默认显示现金账户
      },
      importDialogVisible: false,
      addCashDialogVisible: false,
      addBankDialogVisible: false,

      // 现金表单数据
      cashForm: {
        accountCoding: "", // 资金账户编码
        accountTitle: "", // 资金账户名称
        accountBalance: 0, // 账户余额
        currencyId: "", // 币别id
        subjectId: "", // 会计科目id
        codingState: 1, // 账户状态（1：启用）
        accountSort: 2, // 账户类别（2：现金账户）
      },

      // 银行表单数据
      bankForm: {
        accountCoding: "", // 资金账户编码
        accountTitle: "", // 资金账户名称
        accountBalance: 0, // 账户余额
        bankId: "", // 银行类别id
        cardNumber: "", // 银行卡号
        interconnect: "是", // 银企互联
        createdDate: new Date(), // 绑定日期
        maturityDate: null, // 到期日期
        currencyId: "", // 币别id
        subjectId: "", // 会计科目id
        codingState: 1, // 账户状态（1：启用）
        accountSort: 1, // 账户类别（1：银行账户）
      },

      // 表单验证规则
      cashRules: {
        accountCoding: [
          { required: true, message: "请输入编码", trigger: "blur" },
        ],
        accountTitle: [
          { required: true, message: "请输入账户名称", trigger: "blur" },
        ],
        currencyId: [
          { required: true, message: "请选择币别", trigger: "change" },
        ],
      },

      bankRules: {
        accountCoding: [
          { required: true, message: "请输入编码", trigger: "blur" },
        ],
        bankId: [{ required: true, message: "请选择银行", trigger: "change" }],
        accountTitle: [
          { required: true, message: "请输入账户名称", trigger: "blur" },
        ],
        currencyId: [
          { required: true, message: "请选择币别", trigger: "change" },
        ],
        cardNumber: [
          { required: true, message: "请输入银行卡号", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              // 移除所有空格
              const cardNo = value ? value.replace(/\s/g, "") : "";

              // 验证是否为纯数字
              if (!/^\d+$/.test(cardNo)) {
                callback(new Error("银行卡号只能包含数字"));
                return;
              }

              // 只验证长度（16-19位）
              if (cardNo.length < 16 || cardNo.length > 19) {
                callback(new Error("银行卡号长度应为16-19位"));
                return;
              }

              callback();
            },
            trigger: "blur",
          },
        ],
      },

      // 下拉选项
      currencyOptions: [
        { value: 1, label: "人民币" },
        { value: 2, label: "美元" },
      ],
      bankOptions: [
        { value: 1, label: "工商银行" },
        { value: 2, label: "农业银行" },
      ],
      subjectOptions: [
        { value: 101, label: "库存现金" },
        { value: 102, label: "银行存款" },
      ],

      // 列表数据
      cashList: [],
      bankList: [],

      // 添加分页配置
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
    };
  },

  created() {
    // 页面创建时加载列表数据
    this.loadTableData();
  },

  methods: {
    handleTabClick(tab) {
      this.searchForm = {
        searchKey: "", // 清空搜索关键字
        accountCoding: "",
        accountTitle: "",
        accountSort: tab.name === "cash" ? 2 : 1,
      };
      // 重置分页参数
      this.pagination.currentPage = 1;
      this.loadTableData();
    },

    handleSearch() {
      this.pagination.currentPage = 1; // 重置到第一页
      this.loadTableData();
    },

    loadTableData() {
      // 构建查询参数对象，移除分页参数
      const params = {
        accountCoding: this.searchForm.accountCoding || null,
        accountTitle: this.searchForm.accountTitle || null,
        accountSort: this.activeTab === "cash" ? 2 : 1,
        codingState: 1,
      };

      CapitalAccountList(params)
        .then((response) => {
          if (response.code === 200) {
            let allRecords = [];

            if (Array.isArray(response.data)) {
              allRecords = response.data;
            } else if (response.data && typeof response.data === "object") {
              allRecords = response.data.records || response.data.rows || [];
            }

            // 更新总条数
            this.pagination.total = allRecords.length;

            // 计算当前页的数据
            const start =
              (this.pagination.currentPage - 1) * this.pagination.pageSize;
            const end = start + this.pagination.pageSize;
            const pageRecords = allRecords.slice(start, end);

            // 更新列表数据
            if (this.activeTab === "cash") {
              this.cashList = pageRecords;
            } else {
              this.bankList = pageRecords;
            }

            if (allRecords.length === 0) {
              this.$message.info("未查询到相关数据");
            }
          } else {
            this.$message.error(response.msg || "查询失败");
          }
        })
        .catch((error) => {
          console.error("查询列表失败:", error);
          this.$message.error("查询列表失败");
        });
    },

    showImportDialog() {
      this.importDialogVisible = true;
    },

    showAddCashDialog() {
      this.addCashDialogVisible = true;
      // 重置表单
      if (this.$refs.cashForm) {
        this.$refs.cashForm.resetFields();
      }
      // 获取新编号
      this.getAccountNumber();
    },

    showAddBankDialog() {
      this.addBankDialogVisible = true;
      // 重置表单
      if (this.$refs.bankForm) {
        this.$refs.bankForm.resetFields();
      }
      // 获取新编号
      this.getAccountNumber();
    },

    handleReservation() {
      // 预约开户功能待实现
    },

    downloadTemplate() {
      // 直接调用 this.download 如果它是组件内的方法
      if (this.download && typeof this.download === "function") {
        this.download(
          "/system/account/downloadExcelTemplate",
          {},
          "AccountTemplate.xlsx"
        );
      } else {
        console.error(
          "Download method is not properly defined on the component instance."
        );
      }
    },
    // 定义 download 方法
    download(url, params, filename) {
      axios({
        url: process.env.VUE_APP_BASE_API + url,
        method: "GET",
        responseType: "blob", // Important: Set response type to blob for file downloading
        params: params,
        headers: {
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      })
        .then((response) => {
          const blob = new Blob([response.data], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          });
          const link = document.createElement("a");
          link.href = window.URL.createObjectURL(blob);
          link.download = filename;
          link.click();
          this.$message.success("开始下载模板");
        })
        .catch((error) => {
          console.error("下载模板失败:", error);
          this.$message.error("下载模板失败，请重试");
        });

      // try {
      //   // 获取token
      //   const token = localStorage.getItem('token') || '';

      //   // 使用axios直接发送请求
      //   axios({
      //     url: process.env.VUE_APP_BASE_API + '/system/account/downloadExcelTemplate',
      //     method: 'GET',
      //     responseType: 'blob',  // 重要：设置响应类型为blob
      //     headers: {
      //       'Authorization': `Bearer ${token}`
      //     }
      //   }).then(response => {
      //     // 创建blob链接
      //     const blob = new Blob([response.data], {
      //       type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      //     });

      //     // 创建下载链接
      //     const downloadUrl = window.URL.createObjectURL(blob);
      //     const link = document.createElement('a');
      //     link.href = downloadUrl;
      //     link.download = '资金账户导入模板.xlsx';

      //     // 触发下载
      //     document.body.appendChild(link);
      //     link.click();

      //     // 清理
      //     document.body.removeChild(link);
      //     window.URL.revokeObjectURL(downloadUrl);

      //     this.$message.success('开始下载模板');
      //   }).catch(error => {
      //     console.error('下载模板失败:', error);
      //     this.$message.error('下载模板失败，请重试');
      //   });
      // } catch (error) {
      //   console.error('下载模板失败:', error);
      //   this.$message.error('下载模板失败，请重试');
      // }
    },

    submitCashForm() {
      this.$refs.cashForm.validate((valid) => {
        if (valid) {
          // 构建提交数据
          const submitData = {
            ...this.cashForm,
            accountSort: 2, // 确保账户类型为现金账户
            codingState: 1, // 确保状态为启用
          };

          // 根据是否有id判断是新增还是修改
          const api = submitData.id ? CapitalAccountUpdate : addCapitalAccount;
          const message = submitData.id ? "修改" : "添加";

          // 调用接口
          api(submitData)
            .then((response) => {
              if (response.code === 200) {
                this.$message.success(`${message}成功`);
                this.addCashDialogVisible = false;
                this.loadTableData(); // 重新加载列表数据
                // 重置表单
                this.$refs.cashForm.resetFields();
              } else {
                this.$message.error(response.msg || `${message}失败`);
              }
            })
            .catch((error) => {
              console.error(`${message}现金账户失败:`, error);
              this.$message.error(`${message}失败`);
            });
        }
      });
    },

    submitBankForm() {
      this.$refs.bankForm.validate((valid) => {
        if (valid) {
          // 构建提交数据
          const submitData = {
            ...this.bankForm,
            cardNumber: Number(this.bankForm.cardNumber), // 确保卡号为数字类型
            accountSort: 1, // 确保账户类型为银行账户
            codingState: 1, // 确保状态为启用
          };

          // 根据是否有id判断是新增还是修改
          const api = submitData.id ? CapitalAccountUpdate : addCapitalAccount;
          const message = submitData.id ? "修改" : "添加";

          // 调用接口
          api(submitData)
            .then((response) => {
              if (response.code === 200) {
                this.$message.success(`${message}成功`);
                this.addBankDialogVisible = false;
                this.loadTableData(); // 重新加载列表数据
                // 重置表单
                this.$refs.bankForm.resetFields();
              } else {
                this.$message.error(response.msg || `${message}失败`);
              }
            })
            .catch((error) => {
              console.error(`${message}银行账户失败:`, error);
              this.$message.error(`${message}失败`);
            });
        }
      });
    },

    handleHttpRequest(options) {
      const { file } = options;
      uploadExcel(file, false) // 第二个参数为updateSupport，默认false
        .then((response) => {
          if (response.code === 200) {
            this.$message.success("导入成功");
            this.loadTableData(); // 重新加载列表数据
            this.importDialogVisible = false; // 关闭弹窗
          } else {
            this.$message.error(response.msg || "导入失败");
          }
        })
        .catch((error) => {
          console.error("导入失败:", error);
          this.$message.error("导入失败");
        });
    },

    beforeUpload(file) {
      const isExcel = [
        "application/vnd.ms-excel",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      ].includes(file.type);

      if (!isExcel) {
        this.$message.error("只能上传 Excel 文件!");
        return false;
      }

      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("文件大小不能超过 2MB!");
        return false;
      }

      return true;
    },

    submitUpload() {
      this.$refs.upload.submit();
    },

    // 格式化币别显示
    formatCurrency(row) {
      const currency = this.currencyOptions.find(
        (item) => item.value === row.currencyId
      );
      return currency ? currency.label : row.currencyId;
    },

    // 格式化会计科目显示
    formatSubject(row) {
      const subject = this.subjectOptions.find(
        (item) => item.value === row.subjectId
      );
      return subject ? subject.label : row.subjectId;
    },

    // 格式化银行显示
    formatBank(row) {
      const bank = this.bankOptions.find((item) => item.value === row.bankId);
      return bank ? bank.label : row.bankId;
    },

    handleReset() {
      const currentAccountSort = this.searchForm.accountSort;
      this.searchForm = {
        searchKey: "", // 清空搜索关键字
        accountCoding: "",
        accountTitle: "",
        accountSort: currentAccountSort,
      };
      // 重置分页参数
      this.pagination.currentPage = 1;
      this.loadTableData();
    },

    // 处理编辑按钮点击
    handleEdit(row, type) {
      if (type === "cash") {
        this.cashForm = { ...row };
        this.$refs.cashDialog && (this.$refs.cashDialog.title = "修改现金账户");
        this.addCashDialogVisible = true;
      } else {
        this.bankForm = { ...row };
        this.$refs.bankDialog && (this.$refs.bankDialog.title = "修改银行账户");
        this.addBankDialogVisible = true;
      }
    },

    // 处理删除按钮点击
    handleDelete(row, type) {
      this.$confirm("确认要删除该账户吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 保留原始数据，只修改状态
          const updateData = {
            ...row,
            codingState: 3, // 设置状态为删除
          };

          // 调用更新接口
          CapitalAccountUpdate(updateData)
            .then((response) => {
              if (response.code === 200) {
                this.$message.success("删除成功");
                this.loadTableData(); // 重新加载列表数据
              } else {
                this.$message.error(response.msg || "删除失败");
              }
            })
            .catch((error) => {
              console.error("删除失败:", error);
              this.$message.error("删除失败");
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },

    // 处理每页显示条数变化
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1; // 重置到第一页
      this.loadTableData();
    },

    // 处理页码变化
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.loadTableData();
    },

    // 添加输入框值变化的处理方法
    handleSearchInput(value) {
      // 将输入值同时赋给编码和名称
      this.searchForm.accountCoding = value;
      this.searchForm.accountTitle = value;
    },

    // 处理启用状态变化
    handleStatusChange(val, row) {
      const updateData = {
        ...row,
        codingState: val,
      };

      CapitalAccountUpdate(updateData)
        .then((response) => {
          if (response.code === 200) {
            this.$message.success(val === 1 ? "已启用" : "已禁用");
            this.loadTableData(); // 重新加载列表数据
          } else {
            // 如果更新失败，回滚开关状态
            row.codingState = val === 1 ? 2 : 1;
            this.$message.error(response.msg || "状态更新失败");
          }
        })
        .catch((error) => {
          // 发生错误时，回滚开关状态
          row.codingState = val === 1 ? 2 : 1;
          console.error("状态更新失败:", error);
          this.$message.error("状态更新失败");
        });
    },

    // 修改获取编号的方法
    getAccountNumber() {
      // 根据当前激活的标签页确定账户类型
      const accountSort = this.activeTab === "cash" ? 2 : 1;

      // 调用接口时传入accountSort参数
      number({
        accountSort: accountSort, // 确保参数名称正确
      })
        .then((response) => {
          if (response.code === 200) {
            // 根据当前激活的标签页设置对应表单的编号
            if (this.activeTab === "cash") {
              this.cashForm.accountCoding = response.data;
            } else {
              this.bankForm.accountCoding = response.data;
            }
          } else {
            this.$message.error(response.msg || "获取编号失败");
          }
        })
        .catch((error) => {
          console.error("获取编号失败:", error);
          this.$message.error("获取编号失败");
        });
    },

    // 添加银行卡号格式化方法
    formatCardNumber(e) {
      let value = e.target.value;
      // 移除所有空格
      value = value.replace(/\s/g, "");
      // 只保留数字
      value = value.replace(/[^\d]/g, "");
      // 每4位添加空格
      value = value.replace(/(\d{4})(?=\d)/g, "$1 ");
      // 限制长度（考虑空格，最长为23位）
      value = value.slice(0, 23);
      // 更新值
      this.bankForm.cardNumber = value;
    },

    // 添加跳转方法
    goToDashboard() {
      this.$router.push("/system/account/dashboard");
    },
  },
};
</script>

<style scoped>
.search-box {
  margin-bottom: 20px;
}

.form-content {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.left-content {
  display: flex;
}

.right-content {
  display: flex;
  justify-content: flex-end;
}

.delete-btn {
  color: #f56c6c;
  margin-left: 10px;
}
.delete-btn:hover {
  color: #f78989;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 可以添加一些开关的自定义样式 */
.el-switch {
  margin: 0 auto;
  display: block;
}

/* 添加导入弹框相关样式 */
.import-dialog {
  padding: 20px 0;
}

.import-step {
  display: flex;
  align-items: flex-start;
  margin-bottom: 30px;
}

.step-number {
  width: 24px;
  height: 24px;
  background-color: #409eff;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  margin-right: 15px;
  flex-shrink: 0;
}

.step-content {
  flex: 1;
}

.step-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.download-btn {
  color: #409eff;
  padding: 0;
}

.download-btn:hover {
  color: #66b1ff;
}

.upload-demo {
  margin-top: 10px;
}

/* 调整上传组件的样式 */
:deep(.el-upload-list) {
  margin-top: 10px;
}

:deep(.el-upload-list__item) {
  transition: none;
}
</style>
